import React, { useState, useRef } from 'react';

export const ControlledForm: React.FC = () => {
  const [name, setName] = useState('');

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    alert(`Submitted name: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export const UncontrolledForm: React.FC = () => {
  const nameRef = useRef<HTMLInputElement | null>(null);

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    alert(`Submitted name: ${nameRef.current?.value ?? ''}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export const FormWithValidation: React.FC = () => {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(event.target.value);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!/\S+@\S+\.\S+/.test(email)) {
      setError('Invalid email address');
    } else {
      setError('');
      alert(`Submitted email: ${email}`);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email:
        <input type="text" value={email} onChange={handleChange} />
      </label>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
};

// 示例容器：默认导出一个组合示例，方便在文档页引用
const FormsDemo: React.FC = () => (
  <div style={{ display: 'grid', gap: 20 }}>
    <section>
      <h3>Controlled Form</h3>
      <ControlledForm />
    </section>

    <section>
      <h3>Uncontrolled Form</h3>
      <UncontrolledForm />
    </section>

    <section>
      <h3>Form With Validation</h3>
      <FormWithValidation />
    </section>
  </div>
);

export default FormsDemo;
